package handler

import (
	"api-gate/global"
	__ "api-gate/proto"
	"api-gate/request"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

func Register(c *gin.Context) {
	var req request.Register
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	register, err := global.Rpc.Register(c, &__.RegisterRequest{
		Phone:    req.Phone,
		Password: req.Password,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": register,
	})
	return
}

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	login, err := global.Rpc.Login(c, &__.LoginRequest{
		Phone:    req.Phone,
		Password: req.Password,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": login,
	})
	return
}

func PatientsAdd(c *gin.Context) {
	var req request.PatientsAdd
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	add, err := global.Rpc.PatientsAdd(c, &__.PatientsAddRequest{
		Name:         req.Name,
		Age:          int64(req.Age),
		Symptom:      req.Symptom,
		Hospitalized: req.Hospitalized,
		Discharge:    req.Discharge,
		Doctor:       req.Doctor,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": add,
	})
	return
}

func PatientsList(c *gin.Context) {
	var req request.PatientsList
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	list, err := global.Rpc.PatientsList(c, &__.PatientsListRequest{
		Page: req.Page,
		Size: req.Size,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": list,
	})
	return
}

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	log.Println(file.Filename)
	dst := "./img/" + file.Filename
	// 上传文件至指定的完整文件路径
	c.SaveUploadedFile(file, dst)

}
